""" does the actual conversion """

import os.path, os
from .linker import APILinker, findmodule
from .py_parser import ParseModule
from .rst_to_html import convert_docstr
from .templates import templates
from .formatter import NestedFormatter
from .py_parser import Module

def ispackage(path):
    if os.path.isdir(path) and os.path.exists(os.path.join(path, '__init__.py')):
        return True
    return False

def convertmodule(modulepath, templates, packagepath=None):
    
    print 'Module:', modulepath
    
    # sort out names & paths:
    modulepath = os.path.abspath(modulepath) # for the linker
    moduledir, module = os.path.split(modulepath)
    modulename = module[:-3]
    htmlpath = os.path.join(moduledir, modulename + '.html')
    packagepath = '' if packagepath is None else os.path.abspath(packagepath)
    packagedir, packagename = os.path.split(packagepath)
    if packagename:
        module_rel_parts = os.path.relpath(modulepath[:-3], packagepath).split(os.path.sep)
        module_full_parts = [packagename] + module_rel_parts
        module_fullname = '.'.join(module_full_parts)
    
    # create a linker to handle `links` from this module:
    linker = APILinker(modulepath, packagepath)
       
    # convert the module:
    pyobjects = []
    items = ParseModule(modulepath).parse()
    module = items.pop(0)
    
    for item in items:
        
        # convert the item's properties into a dict of replacement values:
        obj = item._asdict() # nb this copies everything, including ones we will over-ride, which can be confusing when debugging!
        
        # convert docstrings:
        docstr = convert_docstr(item.docstr, linker)
        del obj['docstr']
        obj['docstr.body'] = docstr.body
        obj['docstr.summary'] = docstr.summary
        obj['docstr.fields'] = docstr.fields
        
        # create the fullname:
        obj['fullname'] = module_fullname + '.' + item.qualname
        print obj['fullname'], obj['qualname']
        
        obj['template'] = item.__class__.__name__
        pyobjects.append(obj)
        
        # format args and bases:
        if 'args' in obj:
            obj['args'] = ', '.join(obj['args'])
        if 'bases' in obj:
            obj['bases'] = ', '.join(obj['bases'])
        
    # load common bits into a dict for templates:
    vals = {'pyobjects':pyobjects,
            'module_name':module.name,
            'module_fullname':module_fullname,
            'module_path':module.path,
            }
        
    # make breadcrumbs:
    breadcrumbs = []
    for i in range(len(module_full_parts)):
        text = module_full_parts[i]
        link = '../' * (len(module_full_parts) - i - 2) + '__init__.html'
        breadcrumbs.append({'link':link, 'text':text, 'template':'part'})
    if module_full_parts[-1] == '__init__':
        breadcrumbs.pop(-1)
    vals['breadcrumbs'] = breadcrumbs
    
    # make submodule listing:
    if modulename == '__init__':
        modules = sorted([f[:-3] for f in os.listdir(moduledir) if f.endswith('.py') and f != '__init__.py'])
        subpkgs = sorted([f for f in os.listdir(moduledir) if ispackage(os.path.join(moduledir, f))])
        pkglisting = [{'name':m, 'link':'%s.html' % m, 'template':'submodule'} for m in modules] + \
                     [{'name':p, 'link':'%s/__init__.html' % p, 'template':'subpkg'} for p in subpkgs]
        vals['pkglisting'] = pkglisting
    
    # create the html page:
    formatter = NestedFormatter(templates)
    
    html = formatter.format('init' if modulename == '__init__' else 'module', vals)
    with open(htmlpath, 'w') as htmlfile:
        htmlfile.write(html)
        
    
    